/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.stylefeng.roses.seata.demo.account.modular.controller;

import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.seata.demo.account.modular.service.AccountTblService;
import cn.stylefeng.roses.seata.demo.account.modular.service.TccUpdateAccountService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 账号控制器
 *
 * @author fengshuonan
 * @date 2021/8/28 22:44
 */
@RestController
@Slf4j
public class AccountController {

    @Resource
    private AccountTblService accountTblService;

    @Resource
    private TccUpdateAccountService tccUpdateAccountService;

    /**
     * 更新用户账户的金额
     *
     * @param userId   用户id
     * @param subMoney 减少的金额
     * @author fengshuonan
     * @date 2021/8/29 10:38
     */
    @PostMapping(value = "/account")
    public SuccessResponseData account(@RequestParam("userId") String userId, @RequestParam("subMoney") int subMoney) {

        // 打印出当前的分布式事务id
        log.info("Account Service ... xid: " + RootContext.getXID());

        // 更新余额
        this.accountTblService.updateMoney(userId, subMoney);

        // 测试异常
        if (RandomUtil.randomBoolean()) {
            throw new RuntimeException("this is a mock account Exception");
        }

        return new SuccessResponseData();
    }

    /**
     * 更新用户账户的金额TCC模式
     *
     * @param userId   用户id
     * @param subMoney 减少的金额
     * @author fengshuonan
     * @date 2021/8/29 10:38
     */
    @PostMapping(value = "/tcc/account")
    public SuccessResponseData tccAccount(@RequestParam("userId") String userId, @RequestParam("subMoney") int subMoney) {

        // 打印出当前的分布式事务id
        log.info("Account Service ... xid: " + RootContext.getXID());

        // 更新余额
        this.tccUpdateAccountService.updateAccountTry(userId, subMoney);

        return new SuccessResponseData();
    }

}
